require 'rexml/document'  # ruby stdlib
require 'uri'             # ruby stdlib

module SitemapSpider
  class SitemapRecord
    class ImageRecord
      ATTRIBUTES = [:loc, :caption, :geo_location, :title, :license]
      ATTRIBUTES.each {|a| attr_reader a}

      def initialize(obj)
        if obj.kind_of?(Hash)
          ATTRIBUTES.each do |attr|
            instance_variable_set("@#{attr}", obj[attr])
          end
        else
          ATTRIBUTES.each do |attr|
            if obj.respond_to?(attr)
              instance_variable_set(attr, obj.send(attr))
            end
          end
        end
      end

      def attributes
        (ATTRIBUTES.collect {|a| a if self.send(a)}).compact
      end

      def attribute_to_element(attr)
        e = REXML::Element.new('image:' << attr.to_s)
        e.text = self.send(attr)
        return e
      end

      def to_image_element
        e = REXML::Element.new('image:image')
        attributes.each {|a| e.add_element(attribute_to_element(a))}
        return e
      end

      # Note: only the "location" address is significant
      def ==(oth)
        oth.respond_to?(:loc) and (@loc == oth.loc)
      end
    end
  end
end
